
/**根据字典标识符获取字典
 * @key 字典值
 * @return 字典数组
 */

export const getDict = (key) => {
  if ($store.getters.dictList[key]) return $store.getters.dictList[key]
  console.error('未查询到相关字典')
}

/**根据字典值获取对应标签
 * @key 字典标识符
 * @value 值
 * @return 标签
 */
export const getDictName = (key, value) => {
  let dict = []
  if (Object.prototype.toString.call(key) === '[object Array]') {
    dict = key
  } else {
    dict = $store.getters.dictList[key] || []
  }
  const item = getDataByValue(dict, 'value', value) || {}
  return item.label || item.name || '--'
}

/**根据标签获取对应值
 * @key 字典标识符
 * @label 标签
 * @return 值
 */
export const getDictValue = (key, label) => {
  let dict = []
  if (Object.prototype.toString.call(key) === '[object Array]') {
    dict = key
  } else {
    dict = $store.getters.dictList[key] || []
  }
  // const item = dict.filter(item => item.label === label || item.name === label)[0] || {}
  const item = getDataByValue(dict, 'label', label) || {}
  return item.value || item.id || '--'
}

/**根据自定义字段及输入值，获取对应对象
 * @list 数组
 * @field 自定义字段
 * @value 值
 * @return 返回对应对象
 */
function getDataByValue (list, field, value) {
  let result
  function filterDictName (list, value) {
    for (let item of list) {
      if (item[field] === value) {
        result = item
      }
      if (item.children && item.children.length > 0) {
        if (!result) {
          filterDictName(item.children, value)
        }
      }
    }
  }
  filterDictName(list, value)
  return result || {}
}


/**根据所给标签及值，修改数组属性,
 * @list 需要修改的数组
 * @obj 所给标签，值映射关系{label:value}
 * @return 修改后的数组
 */
function dataMap (list, obj) {
  for (let i = 0; i < list.length; i++) {
    let item = list[i]
    list[i] = {
      ...item
    }
    for (let key in obj) {
      let value = obj[key]
      list[i][key] = item[value]
      if (item.children) {
        list[i].children = item.children
      }
    }
    if (item.children && item.children.length > 0) {
      dataMap(list[i].children, { label: obj.label, value: obj.value })
    }
  }
  return list
}

export default {
  install (Vue) {
    window.$getDataByValue = Vue.prototype.$getDataByValue = getDataByValue
    window.$getDict = Vue.prototype.$getDict = getDict
    window.$getDictName = Vue.prototype.$getDictName = getDictName
    window.$getDictValue = Vue.prototype.$getDictValue = getDictValue
    window.$dataMap = Vue.prototype.$dataMap = dataMap
  }
}
